const qs = require('querystring')
const fs = require('fs')
const path = require('path')
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
  if (req.url === '/api/province') {
    fs.readFile(path.join(__dirname, 'data/province.json'), (err, data) => {
      res.setHeader('Content-Type', 'application/json;charset=utf-8')
      res.end(data.toString())
    })
  } else if (req.url.startsWith('/api/city')) {
    const queryStr = req.url.split('?')[1]
    // 把查询参数字符串 转成 JS 对象结构
    const query = qs.parse(queryStr)
    const pname = query.pname
    console.log(pname)
    fs.readFile(path.join(__dirname,'data/city.json'),(err,data) => {
      const dataObj = JSON.parse(data.toString())
      const cityList = dataObj[pname]
      const cityJson = JSON.stringify(cityList)
      res.setHeader('Content-Type', 'application/json;charset=utf-8')
      res.end(cityJson)
    }
      )
  } else {
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end('你要访问的资源路径不存在')
  }
})
server.listen(2255, () => {
  console.log('Web 服务启动了')
})